package com.beicai.topface.net;

import android.os.Looper;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.widget.Toast;

import com.beicai.topface.callback.ECallBack;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.Executors;

public class EcpssRequest {
    public static void  _RequestE(final String mUrl,final ECallBack mECallBack){
        Executors.defaultThreadFactory().newThread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = null;
                    if(!TextUtils.isEmpty(mUrl)){
                        url = new URL(mUrl);
                    }
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    //设置请求超时时间，单位是毫秒(mm)
                    httpURLConnection.setConnectTimeout(8000);
                    httpURLConnection.setRequestProperty("Content-type", "application/x-javascript->json");//json格式数据
                    httpURLConnection.addRequestProperty("Charset", "UTF-8");//设置字符编码类型
                    httpURLConnection.connect();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                    StringBuilder StringBuilder = new StringBuilder();
                    String request;
                    while ((request = bufferedReader.readLine()) != null) {
                        StringBuilder.append(request);
                    }
                    if(!TextUtils.isEmpty(StringBuilder.toString())){
                        String hs = new String(Base64.decode(StringBuilder.toString().getBytes(), Base64.DEFAULT));
                        JSONObject jsonObject = new JSONObject(hs);
                        if(mECallBack!=null){
                            mECallBack.onSuccess(jsonObject);
                        }
                    }
                    bufferedReader.close();
                    httpURLConnection.disconnect();
                } catch (Exception e) {
                    if(mECallBack!=null){
                        mECallBack.onFail(e);
                    }
                    e.printStackTrace();
                }
            }
        }).start();

    }

}
